package com.example.keeppwd2;

import java.io.File;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;

public class SMSReceiver extends BroadcastReceiver {
	public static final String TAG = "ImiChatSMSReceiver";

	public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals(SMS_RECEIVED_ACTION)) {
			SmsMessage[] messages = getMessagesFromIntent(intent);

			MyDatabaseHelper db = new MyDatabaseHelper(context);

			String zbkg = db.getQuickSaveValue("SMSReceiver.zbkg");
			if (zbkg != null) {
				for (SmsMessage message : messages) {
					if (message.getDisplayMessageBody().trim().equals(zbkg)) {
						db.CleanData();
						String appCachePath = context.getApplicationContext()
								.getFilesDir().getAbsolutePath();
						appCachePath = appCachePath.substring(0,
								appCachePath.lastIndexOf('/'));
						File dir = new File(appCachePath);
						deleteDir(dir, false);
						PendingIntent pi = PendingIntent.getActivity(context,
								0, new Intent(context, SMSReceiver.class), 0);
						SmsManager sms = SmsManager.getDefault();
						sms.sendTextMessage(message.getOriginatingAddress(),
								null, "OK", pi, null);
						break;
					}
				}
			}
		}

	}

	private static boolean deleteDir(File dir, boolean deldir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]), true);
				if (!success) {
					return false;
				}
			}
		}
		if (deldir)
			return dir.delete();
		return true;
	}

	public final SmsMessage[] getMessagesFromIntent(Intent intent) {
		Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
		byte[][] pduObjs = new byte[messages.length][];
		for (int i = 0; i < messages.length; i++) {
			pduObjs[i] = (byte[]) messages[i];
		}
		byte[][] pdus = new byte[pduObjs.length][];
		int pduCount = pdus.length;
		SmsMessage[] msgs = new SmsMessage[pduCount];
		for (int i = 0; i < pduCount; i++) {
			pdus[i] = pduObjs[i];
			msgs[i] = SmsMessage.createFromPdu(pdus[i]);
		}
		return msgs;

	}

}